class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        max_length = 0
        n = len(s)
        d = {}
        left_index = 0
        right_index = 0
        while right_index < n:
            if s[right_index] not in d:
                d[s[right_index]] = right_index
                if len(d) <= k:
                    max_length = max(max_length, right_index - left_index + 1)
                else:
                    while left_index <= right_index:
                        if d[s[left_index]] == left_index:
                            d.pop(s[left_index])
                            left_index += 1
                            break
                        else:
                            left_index += 1
            else:
                d[s[right_index]] = right_index
                max_length = max(max_length, right_index - left_index + 1)
            right_index += 1
        return max_length


data = Solution()
s = "aa"
k = 0
print(data.lengthOfLongestSubstringKDistinct(s, k))